package com.lee.common.utils;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class MakeWord {
	// 代表一个word 程序
	private ActiveXComponent MsWordApp = null;
	// 代表进行处理的word 文档
	private Dispatch document = null;
	// 所选择文档位置
	private Dispatch selection = null;
	// 所选表格
	private Dispatch table = null;

	public MakeWord() {
		// Open Word if we/'ve not done it already
		if (MsWordApp == null) {
			MsWordApp = new ActiveXComponent("Word.Application");
		}
	}

	/**
	 * 设置是否在前台打开 word 程序
	 * 
	 * @param visible
	 *            true or false
	 */
	public void setVisible(boolean visible) {
		MsWordApp.setProperty("Visible", new Variant(visible));
		// 这一句作用相同
		// Dispatch.put(MsWordApp, "Visible", new Variant(visible));
	}

	/**
	 * 创建一个新文档
	 */
	public void createNewDocument() {
		// Find the Documents collection object maintained by Word
		// documents表示word的所有文档窗口，（word是多文档应用程序）
		Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();
		// Call the Add method of the Documents collection to create
		// a new document to edit
		document = Dispatch.call(documents, "Add").toDispatch();
	}

	public void getSelectionDefalut() {
		selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 光标所在位置，默认为起始位置
	}

	public void getSelectionPage1() {
		Dispatch.call(selection, "HomeKey", new Variant(6)); // 文档起始位置
	}

	/**
	 * 选中某个表
	 * 
	 * @param tableIndex
	 *            表在文档中的索引
	 */
	public void getTable(int tableIndex) {
		Dispatch tables = Dispatch.get(document, "Tables").toDispatch();
		// 要填充的表格
		table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();
	}

	/**
	 * 清空选中的表
	 */
	public void deleteTable() {
		table = null;
	}

	/**
	 * 打开一个存在的word文档,并用document 引用 引用它
	 * 
	 * @param wordFilePath
	 *            word文档路径
	 */
	public void openFile(String wordFilePath) {
		// Find the Documents collection object maintained by Word
		// documents表示word的所有文档窗口，（word是多文档应用程序）
		Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();
		document = Dispatch.call(documents, "Open", wordFilePath).toDispatch();
		// document = Dispatch.invoke(documents, "Open", Dispatch.Method,
		// new Object[] { wordFilePath, new Variant(true),
		// new Variant(false)
		// }, new int[1]).toDispatch();
	}

	/**
	 * 向 文档选中位置插入文本内容
	 * 
	 * @param textToInsert
	 *            文本内容
	 */
	public void insertText(String textToInsert) {
		// Get the current selection within Word at the moment.
		// a new document has just been created then this will be at
		// the top of the new doc 获得选 中的内容，如果是一个新创建的文件，因里面无内容，则光标应处于文件开头处
		// 取消选中,应该就是移动光标 ，否则 新添加的内容会覆盖选中的内容
		Dispatch.call(selection, "MoveRight", new Variant(1), new Variant(1));
		// Put the specified text at the insertion point
		Dispatch.put(selection, "Text", textToInsert);
		// 取消选中,应该就是移动光标
		Dispatch.call(selection, "MoveRight", new Variant(1), new Variant(1));
	}

	/**
	 * 在选中位置中插入图片
	 * 
	 * @param jpegFilePath
	 *            图片路径
	 */
	public void insertJpeg(String bookmark, String jpegFilePath) {
		Dispatch bookMarks = Dispatch.call(document, "Bookmarks").toDispatch();
		Dispatch rangeItem = Dispatch.call(bookMarks, "Item", bookmark).toDispatch();
		Dispatch.call(rangeItem, "Select");
		selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
		Dispatch image = Dispatch.get(selection, "InLineShapes").toDispatch();
		Dispatch.call(image, "AddPicture", jpegFilePath);
	}

	/**
	 * 在书签位置中插入word
	 * 
	 * @param bookMark
	 *            书签名称
	 * @param wordFilePath
	 *            要插入的word路径
	 */
	public void insertWord(String bookMark, String wordFilePath) {
		Dispatch bookMarks = Dispatch.call(document, "Bookmarks").toDispatch();
		Dispatch rangeItem = Dispatch.call(bookMarks, "Item", bookMark).toDispatch();
		Dispatch.call(rangeItem, "Select");
		// Dispatch range = Dispatch.call(rangeItem, "Range").toDispatch();
		selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
		Dispatch range = Dispatch.get(selection, "Range").toDispatch();
		Dispatch.call(range, "insertFile", wordFilePath);
	}

	/**
	 * 在word中最后插入段落并设置格式
	 * 
	 * @param text
	 *            要插入的文本
	 */
	public void insertFormatStr(String text) {
		Dispatch wordContent = Dispatch.get(document, "Content").toDispatch(); // 取得word文件的内容
		Dispatch.call(wordContent, "InsertAfter", text);// 插入一个段落到最后
		Dispatch paragraphs = Dispatch.get(wordContent, "Paragraphs").toDispatch(); // 所有段落
		int paragraphCount = Dispatch.get(paragraphs, "Count").changeType(Variant.VariantInt).getInt();// 一共的段落数
		// 找到刚输入的段落，设置格式
		Dispatch lastParagraph = Dispatch.call(paragraphs, "Item", new Variant(paragraphCount)).toDispatch(); // 最后一段（也就是刚插入的）
		// Range 对象表示文档中的一个连续范围，由一个起始字符位置和一个终止字符位置定义
		Dispatch lastParagraphRange = Dispatch.get(lastParagraph, "Range").toDispatch();
		Dispatch font = Dispatch.get(lastParagraphRange, "Font").toDispatch();
		Dispatch.put(font, "Bold", new Variant(true)); // 设置为黑体
		Dispatch.put(font, "Italic", new Variant(true)); // 设置为斜体
		Dispatch.put(font, "Name", new Variant("宋体")); //
		Dispatch.put(font, "Size", new Variant(12)); // 小四
		Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
		Dispatch.call(selection, "TypeParagraph");// 插入一个空行
		Dispatch alignment = Dispatch.get(selection, "ParagraphFormat").toDispatch();// 段落格式
		Dispatch.put(alignment, "Alignment", "2"); // (1:置中 2:靠右 3:靠左)
	}

	/**
	 * 在指定位置添加表格
	 * 
	 * @param row
	 *            要添加表的行数
	 * @param column
	 *            要添加表的列数
	 */
	public void insertTable(int row, int column) {
		// 建立表格
		if (selection != null && document != null) {
			Dispatch tables = Dispatch.get(document, "Tables").toDispatch();
			Dispatch range = Dispatch.get(selection, "Range").toDispatch();// /当前光标位置或者选中的区域
			Dispatch.call(tables, "Add", range, new Variant(row), new Variant(column), new Variant(1)).toDispatch(); // 设置row,column,表格外框宽度
		}
	}

	/**
	 * 在指定的单元格里填写数据
	 * 
	 * @param cellRowIdx
	 *            单元格所在行
	 * @param cellColIdx
	 *            单元格所在列
	 * @param txt
	 *            单元格中要填充的文本
	 */
	public void putTxtToCell(int cellRowIdx, int cellColIdx, String txt) {
		Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx), new Variant(cellColIdx)).toDispatch();
		Dispatch.call(cell, "Select");
		Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
		Dispatch.put(selection, "Text", txt);
	}

	/**
	 * 选中某个单元格
	 * 
	 * @param cellRowIdx
	 *            单元格所在行
	 * @param cellColIdx
	 *            单元格所在列
	 */
	public void getTabaleCell(int cellRowIdx, int cellColIdx) {
		Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx), new Variant(cellColIdx)).toDispatch();
		Dispatch.call(cell, "Select");
		selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
	}

	/**
	 * 在指定的单元格里填写数据
	 * 
	 * @param cellRowIdx
	 *            单元格所在行
	 * @param cellColIdx
	 *            单元格所在列
	 * @param txt
	 *            单元格中要填充的文本
	 * @param color
	 *            文本颜色
	 */
	public void putTxtToCell(int cellRowIdx, int cellColIdx, String txt, String color) {
		Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx), new Variant(cellColIdx)).toDispatch();
		Dispatch.call(cell, "Select");
		Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
		Dispatch.put(selection, "Text", txt);
		Dispatch font = Dispatch.get(selection, "Font").toDispatch();
		Dispatch.put(font, "Color", color);
	}

	/**
	 * 合并两个单元格
	 * 
	 * @param cell1
	 *            单元格1
	 * @param cell2
	 *            单元格2
	 */
	public void mergeCell(Dispatch cell1, Dispatch cell2) {
		Dispatch.call(cell1, "Merge", cell2);
	}

	/**
	 * 合并指定位置的两个单元格
	 * 
	 * @param row1
	 *            单元格1所在行
	 * @param col1
	 *            单元格1所在列
	 * @param row2
	 *            单元格2所在行
	 * @param col2
	 *            单元格2所在列
	 */
	public void mergeCell(int row1, int col1, int row2, int col2) {
		Dispatch cell1 = Dispatch.call(table, "Cell", new Variant(row1), new Variant(col1)).toDispatch();
		Dispatch cell2 = Dispatch.call(table, "Cell", new Variant(row2), new Variant(col2)).toDispatch();
		mergeCell(cell1, cell2);
	}

	/**
	 * 拆分单元格
	 * 
	 * @param rows
	 *            表中第几行
	 * @param culumns
	 *            表中第几列
	 * @param rowCount
	 *            拆分成行数
	 * @param culumnCount
	 *            拆分成列数
	 */
	public void splitCell(int rows, int culumns, int rowCount, int culumnCount) {
		Dispatch cell1 = Dispatch.call(table, "Cell", new Variant(rows), new Variant(culumns)).toDispatch();
		Dispatch.call(cell1, "Split", rowCount, culumnCount);
	}

	/**
	 * 单元格边框设置
	 * 
	 * @param rows
	 *            表中第几行
	 * @param culumns
	 *            表中第几列
	 * @param option
	 *            哪个个边框 1:top,2:left,3:bottom,4:right,5:除最上边最下边外的所有横线,6:
	 *            除最左边和最右边之外的所有竖线,7:左上到右下的斜线,8:左下到右上的斜线
	 * @param width
	 *            边框宽度 1<width<13,0代表没有边框,其他按没有边框算
	 * @param style
	 *            边框样式1:实线,2:虚线
	 */
	public void cellBorder(int rows, int culumns, int option, double width, int style) {
		Dispatch cell = Dispatch.call(table, "Cell", new Variant(rows), new Variant(culumns)).toDispatch();
		Dispatch border = Dispatch.call(cell, "Borders", option).toDispatch();
		if (1 < width && width < 13) {
			Dispatch.put(border, "LineStyle", new Variant(style));
			Dispatch.put(border, "LineWidth", new Variant(width));
			Dispatch.put(border, "Visible", new Variant(true));
		} else {
			Dispatch.put(border, "Visible", new Variant(false));
		}
	}

	/**
	 * 设置选中表中某单元格宽度
	 * 
	 * @param rows
	 *            单元格所在行
	 * @param culumns
	 *            单元格所在列
	 * @param width
	 *            宽度
	 */
	public void cellWidth(int rows, int culumns, double width) {
		Dispatch cell = Dispatch.call(table, "Cell", new Variant(rows), new Variant(culumns)).toDispatch();
		Dispatch.put(cell, "Width", new Variant(width));
	}

	/**
	 * 设置选中表中某单元格宽度
	 * 
	 * @param rows
	 *            单元格所在行
	 * @param culumns
	 *            单元格所在列
	 * @param hight
	 *            高度
	 */
	public void cellHeight(int rows, int culumns, double height) {
		Dispatch cell = Dispatch.call(table, "Cell", new Variant(rows), new Variant(culumns)).toDispatch();
		Dispatch.put(cell, "Height", new Variant(height));
	}

	/**
	 * 设置选中表某行高度
	 * 
	 * @param rows
	 *            所在行
	 * @param height
	 *            高度
	 */
	public void rowHeight(int rowsIndex, double height) {
		Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
		Dispatch row = Dispatch.call(rows, "Item", rowsIndex).toDispatch();
		Dispatch.put(row, "Height", new Variant(height));
	}

	// ========================================================
	/** */
	/**
	 * 把选定的内容或光标插入点向上移动
	 *
	 * @param pos
	 *            移动的距离
	 */
	public void moveUp(int pos) {
		// Dispatch selection = Dispatch.get(MsWordApp,
		// "Selection").toDispatch(); // 输入内容需要的对象
		for (int i = 0; i < pos; i++) {
			// MoveDown MoveLeft moveRight
			// moveStart ( Dispatch.call(selection, "HomeKey", new Variant(6));
			// )
			// moveEnd Dispatch.call(selection, "EndKey", new Variant(6));
			Dispatch.call(selection, "MoveUp");
		}
	}
	
	/** 
	  * 插入文本内容及页眉页脚 
	  * insertText 
	  * @param textToInsert 
	  * @author tf.li 
	  * @data Dec 11, 2010 
	  */
	public void insertViewPages(){
			// Get the current selection within Word at the moment. If
			// a new document has just been created then this will be at
			// the top of the new doc
			Dispatch selection = Dispatch.get(MsWordApp,"Selection").toDispatch();
			//Put the specified text at the insertion point   
			//Dispatch.put(selection,"Text",textToInsert); //插入内容  
	         
	         /****插入页眉页脚*****/  
	         //取得活动窗体对象   
	         Dispatch ActiveWindow = MsWordApp.getProperty( "ActiveWindow").toDispatch();   
	         //取得活动窗格对象   
	         Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane").toDispatch();   
	         //取得视窗对象   
	         Dispatch View = Dispatch.get(ActivePane, "View").toDispatch();   
	           
	         /****设置页眉*****/  
	         Dispatch.put(View, "SeekView", "9");  
	        // Dispatch.put(selection, "Text", ym);  
	  
	         /****设置页脚，动态插入页码*****/  
	         Dispatch.put(View, "SeekView", "10");  
	           
	         final Dispatch Sections = Dispatch.get(document, "Sections").toDispatch();     
	         final Dispatch item = Dispatch.call(Sections, "Item", new Variant(1)).toDispatch();     
	         final Dispatch footer = Dispatch.get(item, "Footers").toDispatch();     
	         final Dispatch f1 = Dispatch.call(footer, "Item", new Variant(1)).toDispatch();     
	         final Dispatch range = Dispatch.get(f1, "Range").toDispatch();     
	         final Dispatch fields = Dispatch.get(range, "Fields").toDispatch();  
	           
	         Dispatch paragraphFormat=(Dispatch) Dispatch.get(selection,"ParagraphFormat").getDispatch();   
	         Dispatch.put(paragraphFormat, "Alignment", 1);  
	         Dispatch.call(fields, "Add", Dispatch.get(selection, "Range").toDispatch(), new Variant(-1), "Page", true).toDispatch();  
	        /* Dispatch.call(selection, "TypeText", "/");  
	         Dispatch.call(fields, "Add", Dispatch.get(selection, "Range").toDispatch(), new Variant(-1), "NumPages",true).toDispatch(); */ 
	         Dispatch font = Dispatch.get(range, "Font").toDispatch();  
	         Dispatch.put(font,"Name",new Variant("宋体_GB2312"));  
	         //Dispatch.put(font, "Bold", new Variant(true));  
	         Dispatch.put(font, "Size", 9);  
	     }

	/** */
	/**
	 * 从选定内容或插入点开始查找文本
	 *
	 * @param toFindText
	 *            要查找的文本
	 * @return boolean true-查找到并选中该文本，false-未查找到文本
	 */
	public boolean find(String toFindText) {
		if (toFindText == null || toFindText.equals(""))
			return false;
		// Dispatch selection = Dispatch.get(MsWordApp,
		// "Selection").toDispatch(); // 输入内容需要的对象
		// 从selection所在位置开始查询
		Dispatch find = Dispatch.call(selection, "Find").toDispatch();
		// 设置要查找的内容
		Dispatch.put(find, "Text", toFindText);
		// 向前查找
		Dispatch.put(find, "Forward", "True");
		// 设置格式
		Dispatch.put(find, "Format", "True");
		// 大小写匹配
		Dispatch.put(find, "MatchCase", "True");
		// 全字匹配
		Dispatch.put(find, "MatchWholeWord", "True");
		// 查找并选中
		return Dispatch.call(find, "Execute").getBoolean();
	}

	/** */
	/**
	 * 把选定选定内容设定为替换文本
	 *
	 * @param toFindText
	 *            查找字符串
	 * @param newText
	 *            要替换的内容
	 * @return
	 */
	public boolean replaceText(String toFindText, String newText) {
		if (!find(toFindText))
			return false;
		// Dispatch selection = Dispatch.get(MsWordApp,
		// "Selection").toDispatch(); // 输入内容需要的对象
		Dispatch.put(selection, "Text", newText);
		return true;
	}

	public void printFile() {
		// Just print the current document to the default printer
		Dispatch.call(document, "PrintOut");
	}

	// 保存文档的更改
	public void save() {
		Dispatch.call(document, "Save");
	}

	/**
	 * 文档另存为
	 * 
	 * @param filename
	 *            文档另存为路径
	 */
	public void saveFileAs(String filename) {
		Dispatch.call(document, "SaveAs", filename);
	}

	/**
	 * 清空文档
	 */
	public void closeDocument() {
		// Close the document without saving changes
		// 0 = wdDoNotSaveChanges
		// -1 = wdSaveChanges
		// -2 = wdPromptToSaveChanges
		if (document != null) {
			Dispatch.call(document, "Close", new Variant(0));
		}
		document = null;
	}

	/**
	 * 退出word程序
	 */
	public void closeWord() {
		if (MsWordApp != null) {
			Dispatch.call(MsWordApp, "Quit");
		}
		MsWordApp = null;
		document = null;
	}

	/**
	 * 清空所选位置
	 */
	public void deleteSelection() {
		selection = null;
	}

	/**
	 * 设置wordApp打开后窗口的位置
	 */
	public void setLocation() {
		Dispatch activeWindow = Dispatch.get(MsWordApp, "Application").toDispatch();
		Dispatch.put(activeWindow, "WindowState", new Variant(1)); // 0=default
		// 1=maximize
		// 2=minimize
		Dispatch.put(activeWindow, "Top", new Variant(0));
		Dispatch.put(activeWindow, "Left", new Variant(0));
		Dispatch.put(activeWindow, "Height", new Variant(600));
		Dispatch.put(activeWindow, "width", new Variant(800));
	}

	/**
	 * 跟据书签选中某位置
	 * 
	 * @param bookmark
	 *            书签名称
	 */
	@SuppressWarnings("deprecation")
	public void selectBookMark(String bookmark) {
		Dispatch bookMarks = Dispatch.call(document, "Bookmarks").toDispatch();
		boolean bookMarkExist = Dispatch.call(bookMarks, "Exists", bookmark).toBoolean();
		if (bookMarkExist) {
			selection = Dispatch.call(bookMarks, "Item", bookmark).toDispatch();
			// Dispatch range = Dispatch.get(selection, "Range").toDispatch();
			// Dispatch.call();
			// selection = Dispatch.call(rangeItem, "Range").toDispatch();
		}
	}

	/**
	 * 在指定行添加一行
	 * 
	 * @param rowIndex
	 *            表中第几行（从1开始）
	 */
	public void addTableRowByRow(int rowIndex) {
		// 表格中所有的行
		Dispatch rows = Dispatch.get(table, "Rows").toDispatch();

		Dispatch row = Dispatch.call(rows, "Item", new Variant(rowIndex)).toDispatch();
		Dispatch.call(rows, "Add", new Variant(row));
	}

	/**
	 * 在指定表中添加一行
	 * 
	 * @param tableIndex
	 *            文档中第几张表（从1开始）
	 */
	public void addTableRow(int tableIndex) {
		// 所有表格
		Dispatch tables = Dispatch.get(document, "Tables").toDispatch();
		// 要填充的表格
		Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex)).toDispatch();
		// 表格中所有的行
		Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
		Dispatch.call(rows, "Add");
	}

	/**
	 * 根据书签插入数据
	 * 
	 * @param bookmarks
	 *            所有书签名
	 * @param valuesb
	 *            插入的数据
	 * @return
	 */

	@SuppressWarnings("deprecation")
	public boolean intoValueBookMark(String[] bookmarks, String[] values) throws Exception {
		if (bookmarks.length != values.length) {
			// 一一对应
			System.out.print("书签必须和值一一对应！");
			return false;
		}
		// Dispatch activeDocument =
		// MsWordApp.getProperty("ActiveDocument").toDispatch();
		Dispatch bookMarks = Dispatch.call(document, "Bookmarks").toDispatch();
		for (int i = 0; i < bookmarks.length; i++) {
			boolean bookMarkExist = Dispatch.call(bookMarks, "Exists", bookmarks[i]).toBoolean();
			if (bookMarkExist) {

				try {
					Dispatch rangeItem = Dispatch.call(bookMarks, "Item", bookmarks[i]).toDispatch();
					Dispatch range = Dispatch.call(rangeItem, "Range").toDispatch();
					Dispatch.put(range, "Text", new Variant(values[i]));
				} catch (Exception e) {
					// 插入标签错误
					// e.printStackTrace();
					System.out.print("插入" + bookmarks[i] + "该书签时错误！");
				}
			} else {
				// 无此标签
				System.out.print("没有" + bookmarks[i] + "该书签！");
				return false;
			}
		}
		return true;
	}

	/**
	 * @param bookmarks
	 *            书签集合
	 * @param values
	 *            文本集合
	 * @param colors
	 *            对应文本颜色集合
	 * @return
	 * @throws Exception
	 */

	@SuppressWarnings("deprecation")
	public boolean intoValueBookMark(String[] bookmarks, String[] values, String[] colors) throws Exception {
		if ((bookmarks.length != values.length) || (bookmarks.length != colors.length)) {
			// 一一对应
			System.out.print("书签必须和值一一对应！");
			return false;
		}
		// Dispatch activeDocument =
		// MsWordApp.getProperty("ActiveDocument").toDispatch();
		Dispatch bookMarks = Dispatch.call(document, "Bookmarks").toDispatch();
		for (int i = 0; i < bookmarks.length; i++) {
			boolean bookMarkExist = Dispatch.call(bookMarks, "Exists", bookmarks[i]).toBoolean();
			if (bookMarkExist) {

				try {
					Dispatch rangeItem = Dispatch.call(bookMarks, "Item", bookmarks[i]).toDispatch();
					Dispatch range = Dispatch.call(rangeItem, "Range").toDispatch();
					Dispatch.put(range, "Text", new Variant(values[i]));
					Dispatch font = Dispatch.get(range, "Font").toDispatch();
					if (!Common.isEmpty(colors[i])) {
						Dispatch.put(font, "Color", colors[i]);
					}
				} catch (Exception e) {
					// 插入标签错误
					// e.printStackTrace();
					System.out.print("插入" + bookmarks[i] + "该书签时错误！");
				}
			} else {
				// 无此标签
				System.out.print("没有" + bookmarks[i] + "该书签！");
				return false;
			}
		}
		return true;
	}

	/**
	 * 
	 * 文档设置水印
	 * 
	 * 
	 * 
	 * @param waterMarkStr
	 *            水印字符串
	 */

	public void setWaterMark(String waterMarkStr) {

		// 取得活动窗格对象
		Dispatch activeWindow = MsWordApp.getProperty("ActiveWindow").toDispatch();
		Dispatch activePan = Dispatch.get(activeWindow, "ActivePane")

		.toDispatch();

		// 取得视窗对象

		Dispatch view = Dispatch.get(activePan, "View").toDispatch();

		// 输入页眉内容

		Dispatch.put(view, "SeekView", new Variant(9));

		Dispatch headfooter = Dispatch.get(selection, "HeaderFooter")

		.toDispatch();

		// 取得图形对象

		Dispatch shapes = Dispatch.get(headfooter, "Shapes").toDispatch();

		// 给文档全部加上水印

		Dispatch shapeselection = Dispatch.call(shapes, "AddTextEffect",

		new Variant(7), waterMarkStr, "宋体", new Variant(1),

		new Variant(false), new Variant(false), new Variant(0),

		new Variant(0)).toDispatch();

		Dispatch.call(shapeselection, "Select");

		// 设置水印参数

		Dispatch shapeRange = Dispatch.get(selection, "ShapeRange").toDispatch();
		//
		Dispatch fill = Dispatch.get(shapeRange, "Fill").toDispatch();

		// 设置水印透明度

		Dispatch.put(fill, "Transparency", new Variant(0));

		Dispatch foreColor = Dispatch.get(fill, "ForeColor").toDispatch();

		// 设置水印颜色

		Dispatch.put(foreColor, "RGB", new Variant(16119285));

		// 设置水印旋转

		Dispatch.put(shapeRange, "Rotation", new Variant(-50));

		Dispatch.put(shapeRange, "LockAspectRatio", new Boolean(true));

		Dispatch.put(shapeRange, "Height", new Variant(117.0709));

		Dispatch.put(shapeRange, "Width", new Variant(468.2835));

		// Dispatch.put(shapeRange, "Left", new Variant(-999995));
		Dispatch.put(shapeRange, "Left", new Variant(-999995));

		Dispatch.put(shapeRange, "Top", new Variant(-999995));

		Dispatch wrapFormat = Dispatch.get(shapeRange, "WrapFormat").toDispatch();

		// 是否允许交叠

		Dispatch.put(wrapFormat, "AllowOverlap", new Variant(true));

		Dispatch.put(wrapFormat, "Side", new Variant(1));

		Dispatch.put(wrapFormat, "Type", new Variant(3));

		Dispatch.put(shapeRange, "RelativeHorizontalPosition", new Variant(0));

		Dispatch.put(shapeRange, "RelativeVerticalPosition", new Variant(0));

		Dispatch.put(view, "SeekView", new Variant(0));

		// ActiveDocument.Sections(1).Range.Select
		// ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
		// Selection.HeaderFooter.Shapes.AddTextEffect( _
		// PowerPlusWaterMarkObject22868437, "保密", "宋体", 1, False, False, 0, 0).
		// _
		// Select
		// Selection.ShapeRange.Name = "PowerPlusWaterMarkObject22868437"
		// Selection.ShapeRange.TextEffect.NormalizedHeight = False
		// Selection.ShapeRange.Line.Visible = False
		// Selection.ShapeRange.Fill.Visible = True
		// Selection.ShapeRange.Fill.Solid
		// Selection.ShapeRange.Fill.ForeColor.RGB = RGB(192, 192, 192)
		// Selection.ShapeRange.Fill.Transparency = 0.5
		// Selection.ShapeRange.Rotation = 315
		// Selection.ShapeRange.LockAspectRatio = True
		// Selection.ShapeRange.Height = CentimetersToPoints(6.89)
		// Selection.ShapeRange.Width = CentimetersToPoints(13.78)
		// Selection.ShapeRange.WrapFormat.AllowOverlap = True
		// Selection.ShapeRange.WrapFormat.Side = wdWrapNone
		// Selection.ShapeRange.WrapFormat.Type = 3
		// Selection.ShapeRange.RelativeHorizontalPosition = _
		// wdRelativeVerticalPositionMargin
		// Selection.ShapeRange.RelativeVerticalPosition = _
		// wdRelativeVerticalPositionMargin
		// Selection.ShapeRange.Left = wdShapeCenter
		// Selection.ShapeRange.Top = wdShapeCenter
		// ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
		//
		//
		//

	}

	/**
	 * word加密
	 * 
	 * @param pwd
	 */
	public void protectedWord(String pwd) {

		String protectionType = Dispatch.get(document, "ProtectionType").toString();
		if (protectionType.equals("-1")) {
			Dispatch.call(document, "Protect", new Variant(3), new Variant(true), pwd);

		}
	}

	/**
	 * 合成的word转pdf
	 * 
	 * @param pdfFile
	 * @return
	 */
	public void word2PDF(String pdfFile) {
		Dispatch.call(document, "ExportAsFixedFormat", pdfFile, 17);// word保存为pdf格式宏，值为17
	}

	/*
	 * 以下为测试用
	 */

	public static void createANewFileTest() {
		MakeWord MakeWord = new MakeWord();
		// word.openWord(true);// 打开 word 程序
		MakeWord.setVisible(true);
		MakeWord.createNewDocument();// 创建一个新文档
		MakeWord.getSelectionDefalut();
		MakeWord.setLocation();// 设置打开后窗口的位置
		MakeWord.insertText("你好");// 向文档中插入字符
		// MakeWord.insertJpeg("E:" + File.separator + "a.jpg"); // 插入图片
		// 如果 ，想保存文件，下面三句
		// word.saveFileAs("d://a.doc");
		// word.closeDocument();
		// word.closeWord();
	}

	public static void openAnExistsFileTest() {
		MakeWord MakeWord = new MakeWord();
		MakeWord.setVisible(true); // 是否前台打开word 程序，或者后台运行
		MakeWord.openFile("d://a.doc");
		// MakeWord.insertJpeg("D:" + File.separator + "a.jpg"); //
		// 插入图片(注意刚打开的word
		// ，光标处于开头，故，图片在最前方插入)
		MakeWord.save();
		MakeWord.closeDocument();
		MakeWord.closeWord();
	}

	public static void insertFormatStr1(String str) {
		MakeWord MakeWord = new MakeWord();
		MakeWord.setVisible(true); // 是否前台打开word 程序，或者后台运行
		MakeWord.createNewDocument();// 创建一个新文档
		MakeWord.insertFormatStr(str);// 插入一个段落，对其中的字体进行了设置
	}

	public static void insertTableTest() {
		MakeWord MakeWord = new MakeWord();
		MakeWord.setVisible(true); // 是否前台打开word 程序，或者后台运行
		MakeWord.createNewDocument();// 创建一个新文档
		MakeWord.setLocation();
		MakeWord.insertTable(3, 2);
		MakeWord.saveFileAs("d://table.doc");
		MakeWord.closeDocument();
		MakeWord.closeWord();
	}

	public static void mergeTableCellTest() {
		insertTableTest();// 生成d://table.doc
		MakeWord MakeWord = new MakeWord();
		MakeWord.setVisible(true); // 是否前台打开word 程序，或者后台运行
		MakeWord.openFile("d://table.doc");

	}

	public static void main(String[] args) {
		// 进行测试前要保证d://a.jpg 图片文件存在
		MakeWord MakeWord = new MakeWord();
		MakeWord.setVisible(false); // 是否前台打开word 程序，或者后台运行
		// MakeWord.openFile("e://20160329需求.docx");
		MakeWord.openFile("D:\\job\\国家重点研发计划战略高技术重点专项课题合同书.docx");

		MakeWord.getSelectionDefalut();
		MakeWord.insertViewPages();

		//MakeWord.setWaterMark("123123123123");
		MakeWord.saveFileAs("d:\\job\\123456.docx");
		System.out.print("chenggong");
		MakeWord.closeDocument();
		MakeWord.closeWord();
		// openAnExistsFileTest();// 打开一个存在 的文件
		// insertFormatStr("格式 化字符串");//对字符串进行一定的修饰
		// insertTableTest();// 创建一个表格
		// mergeTableCellTest();// 对表格中的单元格进行合并
	}
}
